package com.drd.dt.util;

import com.alipay.api.internal.util.codec.Base64;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class EmojiUtil {


    /**
     * 将emojiStr转为 带有表情的字符
     * @param emojiStr
     * @return
     */
    public static String decode(String emojiStr){
       // String result = emojiConverter.toUnicode(emojiStr);

        try {
            if(isBase64(emojiStr)){
                String result =new String(Base64.decodeBase64String(emojiStr), StandardCharsets.UTF_8);
                if(result.contains("�")){//遇到 不可见字符，原样返回，不解析
                    return emojiStr;
                }else{
//                    return result;
                    return EmojiUtil2.getInstance().changeUnicodeFiveToSix(result);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return emojiStr;
    }

    /**
     * 带有表情的字符串转换为编码
     * @param str
     * @return
     */
    public static String encode(String str){

      //  String result=emojiConverter.toAlias(str);

        try {
            String result= null;
            byte[] data=str.getBytes("utf-8");
            if(containsEmoji(str)){
                result = Base64.encodeBase64String(data);
                return result;

            }else {
                if(!isBase64(str)){
                    result = Base64.encodeBase64String(data);
                    return result;
                }
            }




        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    private static boolean isBase64(String str) {
        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        return Pattern.matches(base64Pattern, str);
    }

    public static boolean containsEmoji(String value){
        boolean flag = false;
        try {
            Pattern p = Pattern
                    .compile("[^\\u0000-\\uFFFF]");
            Matcher m = p.matcher(value);
            flag = m.find();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }
}
